package cn.xiaohello.TCP;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 支持多客户端的服务器端实现，为每个接入的客户端提供一个线程来处理请求
 * 
 * @author XIAO
 *
 */
public class MulThreadSocketServerTest {

	public static void main(String[] args) {

		ServerSocket serverSocket = null;
		// 监听端口
		int port = 80;
		try {
			// 建立对本机的端口的监听
			serverSocket = new ServerSocket(port);
			System.out.println("服务器已启动，等待接收数据。。。");

			// 循环不间断监听
			while (true) {
				// 获得链接
				Socket socket = serverSocket.accept();
				// 启动链接处理线程
				new LogicThread_TCP(socket);
				System.out.println("Thread.activeCount(): "
						+ Thread.activeCount());
			}
		} catch (IOException e) {
			// do nothing
		} finally {
			try {
				serverSocket.close();
			} catch (IOException e) {
				// do nothing
			}
		}

	}

}

/**
 * 服务器端逻辑线程，来处理客户机的链接
 * 
 * @author XIAO
 *
 */
class LogicThread_TCP extends Thread {
	private Socket socket = null;

	public LogicThread_TCP(Socket socket) {
		this.socket = socket;
		this.start();
	}

	public void run() {
		InputStream is = null;
		OutputStream os = null;
		try {
			// 创建输入流，准备提取客户机发送（输入）的数据
			is = socket.getInputStream();
			byte[] b = new byte[1024];
			int n = is.read(b);
			// 输出接收到的客户机发送的数据
			System.out.println("客户机发来的信息：" + new String(b, 0, n));
			// 向客户机返回响应数据
			os = socket.getOutputStream();
			os.write(("hello， i am server, " + Thread.currentThread().getName() + " is working...")
					.getBytes());
		} catch (IOException e) {
			// do nothing
		} finally {
			try {
				os.close();
				is.close();
				this.socket.close();
			} catch (IOException e) {
				// do nothing
			}

		}

	}
}
